<script setup lang="ts">
import { ref, computed } from 'vue';
import { onLaunch, onShow, onHide, onReady } from "@dcloudio/uni-app";
import apps from '@/pages/MainViews/app';
import { useMainStore } from '@/store/modules/store';
import { useLoginStore } from '@/store/modules/useLoginStore';
import useThemeEnjoy from '@enjoy/mobile/utils/useTheme';
import { useSystemInfoStore } from '@/store/useSystemInfo';
import { useThemeStore } from '@/store/themeStore';
import { useParamStore } from '@/store/useParamStore';
import { bcmRequest, getBcmUrl } from "@/hooks/bcmServices";
import terminalUtil from "@/common/terminalUtil";
import WebSocketUtil from "@/common/WebSocketUtil";
import Guid from "@/common/guid";
import { handleGetVoiceTypeItem } from "@/common/Voice";
import { useReminderStore } from "@/store/reminderStore";
import { usePrinterStore } from "@/store/printerStore";
import useVoiceTaskStore from "@/store/useVoiceTaskStore";
import usePrintTaskStore from "@/store/usePrintTaskStore";
import service from "@/common/service";
import { getPrintData } from "@/pages/BcmViews/utils/PrintFormatUtil";
import BluetoothPrinter from "@/common/BluetoothPrinter";
import { storeToRefs } from "pinia";
import BcmEventType from "@/pages/BcmViews/common/BcmEventType";
const { setTheme } = useThemeEnjoy();
const systemInfoStore = useSystemInfoStore(); // 系统参数

const mainStore = useMainStore();
const LoginStore = useLoginStore();
const themeStore = useThemeStore(); // 主题
const ParamStore = useParamStore();
const voiceTaskStore = useVoiceTaskStore();
const printTaskStore = usePrintTaskStore();
const printerStore = usePrinterStore();
const reminderStore = useReminderStore();
const { autoPrint, printTimes, bluetoothPrinter } = storeToRefs(printerStore);
const { enable, remindType, voiceStyle, playTimes } = storeToRefs(reminderStore);
let readyForNotice = ref(false);
const noticeTimer = ref<number | null>(null);
let webSocket: WebSocketUtil | null = null


interface Payload {
	c_type?: string;
	c_key?: any;
	c_action?: string;
	c_function?: any;
	c_send_userno?: any;
	c_identity?: any;
	[key: string]: any
}
const self_payload = ref<Payload>({})

const AddModuleUseLog = (title: string, mdName: string, url: string) => {
	if (readyForNotice.value === true) {
		doProcessOpen(title, mdName, url);
	} else {
		const timerId = setInterval(() => {
			if (readyForNotice.value === true) {
				clearInterval(noticeTimer.value);
				noticeTimer.value = null;
				doProcessOpen(title, mdName, url);
			}
		}, 150);
		noticeTimer.value = timerId;
	}
};

// 增加日志
const AddModuleUseLogcb = (list) => {
	const { deviceModel, deviceId } = uni.getSystemInfoSync();
	let request = {
		username: mainStore.loginInfo.sUserName,
		c_userno: mainStore.loginInfo.sUser,
		c_mdcode: list[0].c_mdcode,
		c_mdcname: list[0].c_title,
		c_computername: deviceModel,
		c_enter_dt: null,
		c_guid: "",
		c_ip: deviceId,
		c_leave_dt: null,
		c_login_sessionid: "",
		c_mdname: list[0].c_md_cname,
		c_menu_code: '',
		c_menu_role: "管易通应用",
		c_note: ""

	};
	apps.AddModuleUseLog(request, (res) => {
		if (res && res.data) {
			if (res.data.HasException) { }
		}
	}, () => {
		console.log('失败')
	});
};

const doProcessOpen = (title: string, mdName: string, url: string) => {
	if (mdName) {
		let MenusAndLimitcode = apps.getStorageSync('MenusAndLimitcode') || [];
		const list = MenusAndLimitcode.filter(item => item.c_md_name == mdName);
		if (list.length > 0) {
			mainStore.limitCodeIn(list[0].c_limitcode);
			apps.setStorageSync("sCurProjectName", list[0].c_system);
			if (!list[0].c_limitcode) {
				uni.showToast({
					duration: 3500,
					icon: 'none',
					title: `您没有[${list[0].c_md_cname}]的权限，无法查看消息详情！`,
					mask: true,
				});
				return false;
			}
			ModifyMsgToRead();
			uni.navigateTo({
				url
			});

			AddModuleUseLogcb(list);

		} else {
			uni.showToast({
				duration: 3500,
				icon: 'none',
				title: '您没有' + title + '的模块权限，无法查看消息详情!',
				mask: true
			});
		}
	} else {
		uni.navigateTo({
			url
		});
	}
}

// 标记为已读
const ModifyMsgToRead = () => {
	let Msg = {
		c_identity: self_payload.value.c_identity
	};

	apps.ModifyMsgToRead(Msg, (res) => {
		if (res && res.data) {
			if (res.data.HasException) {
				uni.showToast({
					duration: 3500,
					icon: 'none',
					title: res.data.Exception.Message,
					mask: true,
				});
			}
		}
	}, () => {
		console.log('失败')
	});
}

// 获取主题系统参数
const GetSyscfgByTheme = () => {

	var req = mainStore.enjoyServiceIp;
	try {
		apps.GetSyscfgByTheme(req, res => {
			let _list = [];
			if (!res.HasException && res.ObjectData) {
				if (res.ObjectData && res.ObjectData.ReturnObject) {
					const list = res.ObjectData.ReturnObject;
					let theme: string = '';
					list.forEach((item: any) => {

						if (item.c_class === "管e通v5主题配置") {
							_list.push({
								c_name: item.c_name,
								c_value: item.c_value
							});
						} else if (item.c_name === '管e通v5默认主题') {
							theme = item.c_value === '经典蓝' ? 'theme-blue' : 'theme-orangeRed';
						}
					});
					themeStore.setThemeList(_list);
					const _LocalTheme = uni.getStorageSync('themeVar');
					if (_LocalTheme) {
						themeStore.toggleTheme(_LocalTheme);
						setTheme(_LocalTheme);
					} else {
						themeStore.toggleTheme(theme ? theme : 'theme-blue')
					}
				}
			}
		}, (err) => {
			const theme = uni.getStorageSync('themeVar');
			themeStore.toggleTheme(theme ? theme : 'theme-blue')
			setTheme(theme ? theme : 'theme-blue')
			if (!theme) {
				uni.setStorageSync('themeVar', 'theme-blue');
			}
			console.log(err)
		})
	} catch (e) {
		console.log(e.message);
	}

}

// 是否启用任务管理
const JudgeTaskModule = () => {
	const _taskModuleParam = uni.getStorageSync('taskModuleParam');
	ParamStore.setShowTaskModule(!!_taskModuleParam);
}

onLaunch((e) => {
	//console.log("App Launch********************************************", e);
	systemInfoStore.initFn();
	//初始为尚未登录状态
	mainStore.logout();
	GetSyscfgByTheme();
	JudgeTaskModule();
	const { osName } = uni.getSystemInfoSync();
	// #ifdef APP
	plus.push.addEventListener('receive', function (msg) {
		//click_type=intent时不走receive事件的。
		//console.log('============111111===============收到消息了：' + JSON.stringify(msg));
		let orig_payload = msg.payload && msg.payload.split('|');
		if (orig_payload && orig_payload.length == 6) {
			let self_payload = {
				c_type: orig_payload[0],
				c_key: orig_payload[1],
				c_action: orig_payload[2],
				c_function: orig_payload[3],
				c_send_userno: orig_payload[4],
				c_identity: orig_payload[5],
			}

			self_payload.value = self_payload;
		}

		if (osName == "iOS") {
			if (self_payload) {
				plus.push.createMessage(`${self_payload.c_action}[${self_payload.c_key}]`, self_payload);
			}
		} else {
			let login_data = apps.getStorageSync('login_data');
			if (!login_data.sUser || !login_data.sPassword) {
				uni.showToast({
					duration: 3500,
					icon: 'none',
					title: '请先登录!',
					mask: true
				});
				return false;
			}
			// if (self_payload && self_payload.c_action && self_payload.c_action == '打开巡店登记反馈') {
			// 	AddModuleUseLog('巡店登记反馈', '/pages/MallViews/ShopRegistrationFeedback/index',
			// 		'/pages/MallViews/ShopRegistrationFeedback/detail?c_id=' + msg.payload.c_key + '&where=App')
			// } else {
			// 	AddModuleUseLog('', '', '/pages/OaViews/MessageCenter/index')
			// }
		}
	});
	// #endif
	// #ifdef APP
	//点击通知栏事件
	plus.push.addEventListener('click', function (msg) {
		//click_type=intent时走这里执行
		console.log('============2222222===============点击消息了：' + JSON.stringify(msg));
		/*
			一、android下事件会触发两次：
			第一次msg内容为：
			{
				"__UUID__": "androidPushMsg228159581",
				"title": "整改完成通知",
				"appid": "__UNI__092D5A7",
				"content": "单号：11001-000029，发起人：0295，整改内容：1，整改时间：2024-06-25 19:17:51,罚款金额：0.01",
				"payload": {
				"title": "整改完成通知",
				"content": "单号：11001-000029，发起人：0295，整改内容：1，整改时间：2024-06-25 19:17:51,罚款金额：0.01"
				}
			}
			第二次msg内容为：
			{
				"__UUID__": "androidPushMsg85777626",
				"title": "整改完成通知",
				"appid": "__UNI__092D5A7",
				"content": "单号：11001-000029，发起人：0295，整改内容：1，整改时间：2024-06-25 19:17:51,罚款金额：0.01",
				"payload": "业务通知|11001-000029|打开整改复检|/pages/MallViews/PatrolTask/recheckList|"
			}
			二、ios下只会触发一次，msg内容为：
			{
				"aps": {
				"alert": {
					"body": "单号：11001-000029，发起人：0295，整改内容：1，整改时间：2024-06-25 19:17:51,罚款金额：0.01",
					"title": "整改完成通知"
				},
				"badge": 2,
				"content-available": 0,
				"mutable-content": 1
				},
				"content": "单号：11001-000029，发起人：0295，整改内容：1，整改时间：2024-06-25 19:17:51,罚款金额：0.01",
				"payload": {
				"_ge_": "1",
				"_gmid_": "Qa9uGiZG9O9NFeAKdtfPn,RASS_0625_53e432ee153d588a08b604778b555d18:61046d0ac3294a768fc53396e32c117f:8346e7004e3972cdd2dd75341ee17317",
				"_gurl_": "sdk.open.extension.getui.com:8123"
				},
				"title": "管e通",
				"type": "click"
			}
		*/
		let self_payload = {};
		try {
			let orig_payload = msg.payload && msg.payload.split('|');
			if (orig_payload && orig_payload.length == 6) {
				self_payload = {
					c_type: orig_payload[0],
					c_key: orig_payload[1],
					c_action: orig_payload[2],
					c_function: orig_payload[3],
					c_send_userno: orig_payload[4],
					c_identity: orig_payload[5],
				};
				self_payload.value = self_payload;
			}
		}
		catch (ex) {
			//doNothing
		}
		let login_data = apps.getStorageSync('login_data');
		if (!login_data.sUser || !login_data.sPassword) {
			uni.showToast({
				duration: 3500,
				icon: 'none',
				title: '请先登录!',
				mask: true
			});
			return false;
		}
		const title = msg.aps ? msg.aps.alert.title : self_payload.c_action;
		const id = msg.aps
			? msg.content.substring(msg.content.lastIndexOf('[') + 1, msg.content.lastIndexOf(']'))
			: self_payload.c_key;

		// if (title == '巡店结果通知' || title == '打开巡店登记反馈') {
		// 	AddModuleUseLog('巡店登记反馈', '/pages/MallViews/ShopRegistrationFeedback/index',
		// 		'/pages/MallViews/ShopRegistrationFeedback/detail?c_id=' + id +
		// 		'&where=App')
		// }  else {
		// 	AddModuleUseLog('', '', '/pages/OaViews/MessageCenter/index')
		// }
	});
	// #endif
	setTimeout(() => {
		// uni.setTabBarBadge({
		// 	index: 1,
		// 	text: '31'
		// });
		// uni.showTabBarRedDot({
		// 	index: 3
		// });
	}, 1000);
});
onShow((e) => {
	//console.log("App Show");
	// 设置EnjoyServiceIp地址
	apps.setEnjoyServiceIp((data: any) => {
		mainStore.enjoyServiceIpin(data);
		LoginStore.updateEnjoyIp(data);
	});
	//检查是否需要刷新Token
	apps.IdsTokenRefreshCheck(false);

	// 如果不增加延迟处理，这里无法获取到用户门店信息
	setTimeout(function () {
		initWebSocket();
	}, 3000)
	// 监听切换门店通知
	uni.$on(BcmEventType.SWITCH_STORE, (res) => {
		if(res?.msg == '初始化连接'){
		initWebSocket();
		} else {
		switchStore();
		}
  	})

	uni.$on(BcmEventType.SWITCH_MERCHANT, (res) => {
		switchMerchant();
	})
});
onHide(() => {
	//console.log("App Hide");
});

const initWebSocket = () => {
	let bcmUrl = getBcmUrl();
	let loginInfo = mainStore.loginInfo;
	let socketUrl = bcmUrl.wsApi.startsWith("http") || bcmUrl.wsApi.startsWith("ws") ? bcmUrl.wsApi.replace("http", "ws") : ''; //支持https 替换为 wss
	const wsUrl = socketUrl + '?access_token=' + loginInfo.access_token;
	const terminalId = terminalUtil.getTerminalId();
  let pushModeTmp = service.getStorageSync('pushMode');
  const pushMode = pushModeTmp ? pushModeTmp : '2';
	let curStore = loginInfo?.sDefaultStore ? loginInfo.sDefaultStore : loginInfo.sUserStore;
	let curMerchant = loginInfo?.merchantCode ? loginInfo?.merchantCode : loginInfo?.sDefaultMerchantCode;
	let curStoreHier = loginInfo?.sDefaultStoreHier ? loginInfo.sDefaultStoreHier : loginInfo.sUserStoreHier;
	console.log("initWebSocket:pushMode,socketUrl,loginInfo,terminalId", pushMode, socketUrl, loginInfo, terminalId);

	// 推送模式不等于2 || socketUrl为空 || 机构层级不等于分店 || 门店编码为空 || loginInfo.access_token 为空
	if (pushMode != '2' || !socketUrl || curStoreHier != '2' || !curStore && !terminalId || !loginInfo.access_token) {
		console.warn("initWebSocket:webSocket不满足连接条件:pushMode,socketUrl,curStoreHier,curStore,terminalId,access_token", pushMode, socketUrl, curStoreHier, curStore, terminalId, loginInfo.access_token);
		if (webSocket != null) {
			webSocket.destroy();
			webSocket = null;
		}
		return;
	}

	if (webSocket != null) {
		console.warn("initWebSocket:webSocket对象已存在，无需初始化:webSocket", webSocket);
		return;
	}

	webSocket = new WebSocketUtil(wsUrl, 60, curStore, terminalId, 'APP', curMerchant);
	// 可以注册消息回调
	webSocket.onMessage(data => {
		//console.log('Received data:', data);
		handleMessage1(data);
	});
}
// 切换门店
const switchStore = () => {
	console.log("app.vue:switchStore 更新门店,mainStore.loginInfo", mainStore.loginInfo);
	if (webSocket == null) {
		initWebSocket()
	} else {
		let loginInfo = mainStore.loginInfo;
		let curStore = loginInfo?.sDefaultStore ? loginInfo.sDefaultStore : loginInfo.sUserStore;
		let curMerchant = loginInfo.merchantCode ? loginInfo.merchantCode : loginInfo.sDefaultMerchantCode;
		webSocket.switchStore(curStore);
		if (curMerchant){
			webSocket.switchMerchantCode(curMerchant)
		}
	}
}


const switchMerchant = () => {
	console.log("app.vue:switchMerchant", mainStore.loginInfo);
	if (webSocket == null) {
		initWebSocket()
	} else {
		let loginInfo = mainStore.loginInfo;
		let curMerchant = loginInfo?.merchantCode ? loginInfo?.merchantCode : loginInfo?.sDefaultMerchantCode;
		if (curMerchant) {
			webSocket.switchMerchantCode(curMerchant)
		}
	}
}


const handleMessage1 = (event: any) => {
	console.log("event", event);
	let messageObject = JSON.parse(JSON.parse(event)?.Payload);
	console.log("handleMessage1:messageObject?.messageType,messageObject", messageObject?.messageType, messageObject);
	if (!!messageObject && messageObject?.messageType != 'terminalHeartbeat') {
		// 接收到新消息后刷新"订单处理"页面
		if (['newPickupTask'].includes(messageObject.messageType) && mainStore.loginInfo?.workStatus == '1') {
			uni.$emit(BcmEventType.REFRESH_PICK_TASK_LIST, { msg: '刷新页面' });
		} else if (['newReviewTask'].includes(messageObject.messageType) && mainStore.loginInfo?.workStatus == '1') {
			uni.$emit(BcmEventType.REFRESH_REVIEW_TASK_LIST, { msg: '刷新页面' });
		} else if (['terminalTest'].includes(messageObject.messageType)) {
      uni.$emit(BcmEventType.TEST_WEB_SOCKET, { msg: 'WebSocket消息测试' });
    } else {
			uni.$emit(BcmEventType.REFRESH_ORDER_LIST, { msg: '刷新页面' });
		}
    if (enable.value) {
      if (mainStore.loginInfo?.workStatus == '1') {
        addVoiceTaskFn(Guid.NewGuid().ToString(), messageObject.messageType)
      } else {
        if (!['newPickupTask', 'newReviewTask'].includes(messageObject.messageType)) {
          addVoiceTaskFn(Guid.NewGuid().ToString(), messageObject.messageType)
        }
      }
    }
		if (autoPrint.value && bluetoothPrinter.value.deviceId && messageObject.message.length > 0) {
			if (['newOrder', 'newPreOrder', 'orderCancelApply', 'orderRefundApply'].includes(messageObject.messageType)) {
				messageObject.message?.map(async (v: any) => {
					// console.log("handleMessage1:'newOrder', 'newPreOrder' v", v);
					await addPrintTaskFn(v, ['orderCancelApply', 'orderRefundApply'].includes(messageObject.messageType) ? 'afs' : 'order', true)
				})
			}
		}
	}
}
const addVoiceTaskFn = (id: number, v: any) => {
	let voice = handleGetVoiceTypeItem(v)
	// console.log("addVoiceTaskFn,voice", voice);
	if (!!voice) {
		// @ts-ignore todo xiaoch 需要解决类型问题报红
		let curPlayTimes = playTimes.value[voice.name] >= 0 ? playTimes.value[voice.name] : 1;
		if (curPlayTimes > 0) {
			voiceTaskStore.addVoiceTask({
				id,
				remindType: remindType.value,
				path: 'static/audio/' + voiceStyle.value + '/' + voice.file,
				times: curPlayTimes
			})
		}
	}
}

const addPrintTaskFn = async (v: any, type = 'order', isAutoPrint = false) => {
	// console.log("addPrintTaskFn:dataList0,v", v);
	printTaskStore.addTask({
		id: type == 'order' ? v.orderNo : v.afsOrderNo,
		task: async () => new Promise(async (resolve) => {
			let dataList: any[];
			if (type == 'order') {
				dataList = await handlePreQueryOrderPrint([v.orderNo])
			} else {
				dataList = await handlePreQueryAfsOrderPrint([v.afsOrderNo]);
			}
			// console.log("addPrintTaskFn:dataList", dataList);
			if (dataList.length == 0) {
				resolve();
			} else {
				v = dataList[0];
				let data = getPrintData(v, type, printTimes.value), skip = '0';
				BluetoothPrinter.setDevice(bluetoothPrinter.value).checkAndPrint(data).then((res: any) => {
					if (res.code == '0') {
						if (type == 'afs') {
							ConfirmAfsOrderPrint(v, skip)
						} else {
							ConfirmOrderPrint(v, skip)
						}
						// 打印完成之后在通知页面刷新
						uni.$emit(BcmEventType.REFRESH_ORDER_LIST, { msg: '刷新页面' });
					}
					resolve()
				}).catch((res: any) => {
					console.log(res);
					if (!isAutoPrint) {
						// skipFunc(res?.msg);
					}
				})
			}
		})
	})
}

const handlePreQueryOrderPrint = async (idList: any[]) => {
	let params = {
		orderNoList: idList,
		operateMode: '自动',
		operateTerminal: 'APP'
	}
	const bcmUrl = getBcmUrl();
	const response: any = await bcmRequest(bcmUrl.orderApi, '订单表', 'PreQueryOrderAutoPrint', params);
	let arr: any[] = []
	response?.filter((v: any) => v.status == '1')?.map((v: any) => {
		arr.push(v.bcmOrder)
	})
	console.log("handlePreQueryOrderPrint:arr", arr);
	return arr
}

const handlePreQueryAfsOrderPrint = async (idList: any[]) => {
	let params = {
		afsOrderNoList: idList,
		operateMode: '自动',
		operateTerminal: 'APP'
	}
	const bcmUrl = getBcmUrl();
	const response: any = await bcmRequest(bcmUrl.orderApi, '售后单表', 'PreQueryAfsOrderAutoPrint', params);
	let arr: any[] = []
	response?.filter((v: any) => v.status == '1')?.map((v: any) => {
		arr.push(v.bcmAfsOrder)
	})
	// console.log("handlePreQueryAfsOrderPrint:arr", arr);
	return arr
}

const ConfirmAfsOrderPrint = async (v: any, skipPrintFlag = '0') => {
	await orderAction({
		uniqueKey: '售后单表',
		methodName: 'ConfirmAfsOrderPrint'
	}, v, {
		afsOrderNo: v.afsOrderNo,
		afsOrderId: v.afsOrderId,
		BillId: v.afsOrderId,
		thirdAfsOrderNo: v.thirdAfsOrderNo,
		extras: {
			operateMode: '自动',
			operateTerminal: 'APP',
			skipPrintFlag
		}
	})
}

const ConfirmOrderPrint = async (v: any, skipPrintFlag = '0') => {
	await orderAction({
		uniqueKey: '订单表',
		methodName: 'confirmOrderPrint'
	}, v, {
		operateMode: '自动',
		operateTerminal: 'APP',
		skipPrintFlag
	})
}

const orderAction = async (option: { uniqueKey: string, methodName: string }, v: any, params: any = undefined, text = '', popup = false, fn: any = undefined) => {
	service.enjoyShowLoading('正在加载...');
	let param = {
		chnlCode: v.chnlCode,
		chnlType: v.chnlType,
		orderNo: v.orderNo,
		storeCode: v.storeCode,
		thirdOrderNo: v.thirdOrderNo,
		orderId: v.orderId,
		...params,
	}
	const bcmUrl = getBcmUrl();
	const response = await bcmRequest(bcmUrl.orderApi, option.uniqueKey, option.methodName, param);
	service.enjoyHideLoading();
	if (text) {
		uni.showToast({
			title: text,
			icon: 'none'
		});
	}
	if (popup) {
		// close()
	}
	if (fn) {
		fn(v)
	}
	if (params) {
		return response
	}
}
</script>
<style lang="scss">
@import "@enjoy/mobile/styles/index";
@import "@/common/scss/app.scss";
</style>
